package com.atguigu.gmall.mq.receiver;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Configuration
public class MessageReceiver {

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "gmall_queue",autoDelete = "false"),
            exchange = @Exchange(value = "exchange.confirm",autoDelete = "false"),
            key={"routeing.confirm"}
    ))
    public void receiverMessage(Message message, Channel channel) throws IOException {
        System.out.println("message="+new String(message.getBody()));
        try{
            int i = 1/0;
            //false确定一个消息,true批量确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
                if(message.getMessageProperties().getRedelivered()) {
                    System.out.println("消息已重复处理,拒绝再次接收");
                    channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
                }else{
                    System.out.println("消息即将再次返回队列处理");
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
                }
        }
    }

}
